<template>
  <ul class="list">
    <li class="item"
      v-for="(item) of letters"
      :key="item"
      :ref="item"
      @click="handleLetterClick"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      {{item}}
    </li>
  </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  // 参数cities从开始的空数据到ajax调用得到数据，本组件会渲染两次，这时候update方法会被触发
  updated () {
    // 字母A距离头部蓝色框的高度
    this.startY = this.$refs['A'][0].offsetTop
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        // 函数节流，降低调用频率
        if (this.timer) {
          // 清除原来正在执行的方法
          clearTimeout(this.timer)
        }
        setTimeout(() => {
          // 79是头部蓝色框的高度
          const touchY = e.touches[0].clientY - 79
          // 20是每个字母高度
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
   @import '~styles/varibles.styl'
   .list
     // 弹性布局,子元素的float、clear和vertical-align属性将失效
     display: flex
     // 弹性布局特性： 让元素沿垂直主轴从上到下垂直排列
     flex-direction: column
     // 弹性布局特性： 元素在主轴（页面）上居中排列
     justify-content: center
     position: absolute
     top: 1.58rem
     right: 0
     bottom: 0
     width: .4rem
     .item
       line-height: .4rem
       text-align: center
       color: $bgColor
</style>
